import KoaBootLogger from "@framework/web/KoaBootLogger";
import {Sequelize} from "sequelize-typescript";
import Path from "node:path";
import KoaBootFile from "@framework/web/KoaBootFile";
import GlobalAutoConfigurable from "@framework/config/GlobalAutoConfigurable";

/**
 * Mysql 封装
 */
class KoaBootMysql {

    /**
     * 日志类
     * @private
     */
    private logger: KoaBootLogger = KoaBootLogger.getInstance();

    /**
     * Sequelize ORM 框架
     * @private
     */
    private sequelize: Sequelize;

    /**
     * 构造函数
     */
    constructor() {
        this.sequelize = new Sequelize(GlobalAutoConfigurable.koaBoot.mysql.database, GlobalAutoConfigurable.koaBoot.mysql.username, GlobalAutoConfigurable.koaBoot.mysql.password, {
            host: GlobalAutoConfigurable.koaBoot.mysql.host,
            port: GlobalAutoConfigurable.koaBoot.mysql.port,
            define: {
                timestamps: GlobalAutoConfigurable.koaBoot.mysql.default.timestamps,
                createdAt: GlobalAutoConfigurable.koaBoot.mysql.default.createdAt,
                updatedAt: GlobalAutoConfigurable.koaBoot.mysql.default.updatedAt,
                deletedAt: GlobalAutoConfigurable.koaBoot.mysql.default.deletedAt
            },
            pool: {
                max: GlobalAutoConfigurable.koaBoot.mysql.pool.max,
                min: GlobalAutoConfigurable.koaBoot.mysql.pool.min,
                acquire: GlobalAutoConfigurable.koaBoot.mysql.pool.acquire,
                idle: GlobalAutoConfigurable.koaBoot.mysql.pool.idle
            },
            logging: msg => this.logger.debug(msg),
            dialectOptions: {
                charset: GlobalAutoConfigurable.koaBoot.mysql.default.charset
            },
            dialect: 'mysql',
            models: [Path.join(KoaBootFile.getRootPath(), `src/main/app/${GlobalAutoConfigurable.koaBoot.mysql.modelDir}`)]
        });
    }

    /**
     * 监听 mysql 链接
     */
    public async onMysql(): Promise<string> {
        return new Promise<string>(((resolve, reject) => {
            this.sequelize.authenticate()
                .then(() => {
                    resolve("success");
                })
                .catch(error => {
                    this.logger.error("Initialize " + error);
                    resolve("error");
                })
        }));
    }
}

export default KoaBootMysql;